/*
 * @lc app=leetcode.cn id=564 lang=typescript
 *
 * [564] 寻找最近的回文数
 */

// @lc code=start
function nearestPalindromic(n: string): string {
  // 计算所有可能的回文数
  const getCandidates = (n: string): number[] => {
    const len = n.length;
    const candidates = new Array<number>();
    // 初始化，将涉及到进退位的最近的回文数先加入
    candidates.push(10 ** (len - 1) - 1);
    candidates.push(10 ** len + 1);

    let selfPrefix = Number(n.substring(0, ((len + 1) / 2) >> 0));
    const selfPrefixs = [selfPrefix - 1, selfPrefix, selfPrefix + 1];
    for (const x of selfPrefixs) {
      const prefix = x.toString();
      const candidate =
        prefix +
        prefix
          .split('')
          .reverse()
          .join('')
          .substring(len % 2);
      candidates.push(Number(candidate));
    }
    return candidates;
  };

  let selfNumber = Number(n);
  let ans = -1;
  const candidates: number[] = getCandidates(n);
  for (const x of candidates) {
    if (x === selfNumber) continue;
    if (ans === -1) ans = x;
    if (Math.abs(x - selfNumber) < Math.abs(ans - selfNumber)) ans = x;
    if (Math.abs(x - selfNumber) === Math.abs(ans - selfNumber)) {
      ans = Math.min(ans, x);
    }
  }

  return String(ans);
}
// @lc code=end
